<?php

namespace App\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use common\utils\SysCode;
use App\Exceptions\CustomException;

class ResponseMiddleware
{
    // 统一数据格式
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        // 自定义错误
        if ($response->exception instanceof CustomException) {
            return $response;
        }
        $status = $response->status();
        $content = $response->getOriginalContent();
        switch ($status) {
            case Response::HTTP_OK://200
                $response->setContent(output($content));
                break;
            case SysCode::UNAUTHORIZED://401
            case SysCode::FORBIDDEN://403
            case SysCode::NOT_FOUND://404
                $response->setContent(output('', $status));
                break;
            case Response::HTTP_METHOD_NOT_ALLOWED://405
                $response->setContent(output('', SysCode::NOT_FOUND))->setStatusCode(SysCode::NOT_FOUND);
                break;
            case Response::HTTP_UNPROCESSABLE_ENTITY://422
                $response->setContent(output($content, SysCode::INVALID_ARGUMENT));
                break;
        }
        return $response;
    }
}
